package com.ruoyi.wzgl.wzrk.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.echarts.EChartsBt;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.WordUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.wzgl.wzrk.domain.Wzrk;
import com.ruoyi.wzgl.wzrk.domain.WzrkRkmx;
import com.ruoyi.wzgl.wzrk.service.IWzrkService;
import com.ruoyi.wzgl.wzrk.vo.RkZeByMonthVo;
import com.ruoyi.wzgl.wzrk.vo.WzRklVo;
import com.ruoyi.wzgl.wzxx.domain.Wzxx;
import com.ruoyi.wzgl.wzxx.service.IWzxxService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 物资入库Controller
 *
 * @author huacai
 * @date 2024-09-23
 */
@RestController
@RequestMapping("/wzgl/wzrk")
public class WzrkController extends BaseController {
    @Resource
    private IWzrkService wzrkService;

    @Resource
    private IWzxxService wzxxService;

    /**
     * 查询物资入库列表
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:list')")
    @GetMapping("/list")
    public TableDataInfo list(Wzrk wzrk) {
        startPage();
        List<Wzrk> list = wzrkService.selectWzrkList(wzrk);
        return getDataTable(list);
    }

    /**
     * 导出物资入库列表
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:export')")
    @Log(title = "物资入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Wzrk wzrk) {
        List<Wzrk> list = wzrkService.selectWzrkList(wzrk);
        List<Wzrk> resultList = new ArrayList<>();
        for(Wzrk item : list){
            Wzrk result = wzrkService.selectWzrkByWzrkId(item.getWzrkId());
            result.setWzrkRkmxList(result.getWzrkRkmxList()); // 设置查询到的子表数据到主表对象中
            resultList.add(result); // 将查询结果添加到结果集合中
        }
        ExcelUtil<Wzrk> util = new ExcelUtil<Wzrk>(Wzrk.class);
        util.exportExcel(response, resultList, "物资入库数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Wzrk> util = new ExcelUtil<Wzrk>(Wzrk.class);
        util.importTemplateExcel(response, "物资入库数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "物资入库", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Wzrk> util = new ExcelUtil<Wzrk>(Wzrk.class);
        InputStream inputStream = file.getInputStream();
        List<Wzrk> list = util.importExcel(inputStream);
        inputStream.close();
        int count = wzrkService.batchInsertWzrk(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取物资入库详细信息
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:query')")
    @GetMapping(value = "/{wzrkId}")
    public AjaxResult getInfo(@PathVariable("wzrkId") Integer wzrkId) {
        return success(wzrkService.selectWzrkByWzrkId(wzrkId));
    }

    /**
     * 新增物资入库
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:add')")
    @Log(title = "物资入库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Wzrk wzrk) {
        wzrk.setUserId(Math.toIntExact(getUserId()));
        wzrk.setDeptId(Math.toIntExact(getDeptId()));
        wzrk.setCreateBy(getUsername());
          // 获取当前时间
//        LocalDateTime now = LocalDateTime.now();
//        // 定义日期时间格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//        // 格式化当前时间
//        String formattedNow = now.format(formatter);
        return toAjax(wzrkService.insertWzrk(wzrk));
    }

    /**
     * 修改物资入库
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:edit')")
    @Log(title = "物资入库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Wzrk wzrk) {
        return toAjax(wzrkService.updateWzrk(wzrk));
    }

    /**
     * 删除物资入库
     */
    @PreAuthorize("@ss.hasPermi('wzgl:wzrk:remove')")
    @Log(title = "物资入库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{wzrkIds}")
    public AjaxResult remove(@PathVariable Integer[] wzrkIds) {
        return toAjax(wzrkService.deleteWzrkByWzrkIds(wzrkIds));
    }

    /**
     * 根据模板导出word
     *
     * @param response
     * @return
     */
    @Log(title = "根据模板导出word", businessType = BusinessType.EXPORT)
    @GetMapping("/exportWord/{wzrkId}")
    public AjaxResult exportWord(@PathVariable("wzrkId") Integer wzrkId, HttpServletRequest request, HttpServletResponse response) {
        Wzrk wzrk = wzrkService.selectWzrkByWzrkId(wzrkId);
        String rkFs = wzrk.getRkFs(); //入库方式
        // 创建一个 SimpleDateFormat 对象，并指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date rkTimeDate = wzrk.getRkTime();
        String rkTime = sdf.format(rkTimeDate); //入库日期
        String rkZt = wzrk.getRkZt(); //入库状态
        String rkName = wzrk.getRkName(); //入库人

        //入库明细
        List<WzrkRkmx> wzrkRkmxList = wzrk.getWzrkRkmxList();

        Map<String, Object> map = new HashMap<>();

        map.put("rkFs", rkFs);
        map.put("rkTime", rkTime);
        map.put("rkZt", rkZt);
        map.put("rkName", rkName);
        map.put("wzrkRkmxList", wzrkRkmxList);

        String str = UUID.randomUUID().toString() + ".docx";
        //获取yml配置地址
        String tempDir = RuoYiConfig.getProfile() + "/upload/";
        String name = WordUtil.easyPoiExport("static/word/wzrk.docx", tempDir, str, map, request, response);
        return AjaxResult.success(name);
    }


    /**
     * 确定入库
     */
    @PutMapping("/qdrk/{wzrkId}")
    @Transactional
    public AjaxResult qdrk(@PathVariable("wzrkId") Integer wzrkId) {
        Wzrk wzrk = wzrkService.selectWzrkByWzrkId(wzrkId);
        List<WzrkRkmx> wzrkRkmxList = wzrk.getWzrkRkmxList();
        for (WzrkRkmx wzrkRkmx : wzrkRkmxList) {
            Integer wzxxId = wzrkRkmx.getWzxxId(); //物资信息ID
            Wzxx wzxx = wzxxService.selectWzxxByWzxxId(wzxxId);
            Integer kc = wzxx.getKc(); //入库前的库存
            Integer rkSl = wzrkRkmx.getRkSl(); //入库数量
            Wzxx wzxxUp = new Wzxx();
            wzxxUp.setWzxxId(wzxxId);
            wzxxUp.setKc(kc + rkSl);
            wzxxService.updateWzxx(wzxxUp);
        }
        Wzrk wzrkUp = new Wzrk();
        wzrkUp.setWzrkId(wzrkId);
        wzrkUp.setRkZt("入库完成");
        wzrkUp.setWzrkRkmxList(wzrkRkmxList);
        return toAjax(wzrkService.updateWzrk(wzrkUp));
    }

    /**
     * 查询本月入库单量
     */
    @GetMapping("/getByRkDl")
    public AjaxResult getByRkDl() {
        String byRkDl = wzrkService.getByRkDl();
        return success(byRkDl);
    }

    /**
     * 查询本月出库单量
     */
    @GetMapping("/getByCkDl")
    public AjaxResult getByCkDl() {
        Integer byCkDl = wzrkService.getByCkDl();
        return success(byCkDl);
    }

    /**
     * 采购物资数量top10
     */
    @GetMapping("/selectWzRkl")
    public AjaxResult selectWzRkl() {
        List<EChartsBt> result = new ArrayList<>();

        List<WzRklVo> wzRklVos = wzrkService.selectWzRkl();
        for (WzRklVo wzRklVo : wzRklVos) {
            EChartsBt eChartsBt = new EChartsBt();
            eChartsBt.setName(wzRklVo.getWzName());
            eChartsBt.setValue(wzRklVo.getRkSl());
            result.add(eChartsBt);
        }

        return success(result);
    }

    /**
     * 近6个月每个月的总额
     */
    @GetMapping("/selectRkZeByMonth")
    public AjaxResult selectRkZeByMonth() {
        List<EChartsBt> result = new ArrayList<>();

        List<RkZeByMonthVo> rkZeByMonthVos = wzrkService.selectRkZeByMonth();
        for (RkZeByMonthVo rkZeByMonthVo : rkZeByMonthVos) {
            EChartsBt eChartsBt = new EChartsBt();
            eChartsBt.setName(rkZeByMonthVo.getYf());
            eChartsBt.setValue(String.valueOf(rkZeByMonthVo.getRkZe()));
            result.add(eChartsBt);
        }

        return success(result);
    }

}
